package com.dupf.common.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

import java.util.List;

/**
 * 校验中国手机号
 * Created by dupf on 2018/3/22.
 */
public class ChinaMobileValidator extends ValidatorHandler<String> implements Validator<String> {
    private static final String CHINA_PHONE_PREFIX = "134,135,136,137,138,139,141,143,147,148,150,151,152,154,157,158,159,178,182,183,184,187,188,198,130,131,132,145,146,155,156,166,171,175,176,185,186,133,149,153,173,174,177,180,181,189,199,170,179";

    private String fieldName;

    public ChinaMobileValidator(String fieldName) {
        this.fieldName = fieldName;
    }

    @Override
    public boolean validate(ValidatorContext context, String mobilePhone) {

        boolean isValidPhone = false;
        if (mobilePhone == null) {
            isValidPhone = false;
        } else {

            for (String pre : CHINA_PHONE_PREFIX.split(",")) {

                if (mobilePhone.startsWith(pre)) {
                    isValidPhone = true;
                    break;
                }
            }
        }

        if (!isValidPhone) {
            context.addError(ValidationError.create(String.format("%s必须是中国手机号", fieldName))
                    .setErrorCode(-1)
                    .setField(fieldName)
                    .setInvalidValue(mobilePhone));
            return false;
        }
        return true;
    }

}
